package com.ocom.company.controller;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.constant.HumanServiceUrl;
import com.ocom.common.dto.*;
import com.ocom.common.entity.company.*;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.*;
import com.ocom.common.resp.Result;
import com.ocom.common.response.GetComRequestResponse;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.company.ComDockApiListVo;
import com.ocom.common.vo.company.ComLoginAuthCodeRequest;
import com.ocom.common.vo.company.DockApiUrlVo;
import com.ocom.common.vo.company.SrvCodeVo;
import com.ocom.company.service.*;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2023/3/21
 **/
@Slf4j
@RestController
public class DockController {


	@Autowired
	CompanyDockService companyDockService;

	@Autowired
	DockServerService dockServerService;

	@Autowired
	DockKeyService dockKeyService;

	@Autowired
	ComDockApiService comDockApiService;

	@Autowired
	DockApiService dockApiService;

	@Autowired
	DockUrlService dockUrlService;

	@Resource
	RedisUtil redisUtil;

	@PostMapping(CompanyServiceUrl.URL_getReplyApiPara)
	public Result getReplyApiPara(@RequestBody GetReplyApiParaRequest request) {

		log.info("getReplyApiParaResult:" + request.toString());

		EntityCompanyDock entityCompanyDock = null;
		if(request.getComId()>0l){
			entityCompanyDock = companyDockService.getCompanyDockInfo(request.getComId(), request.getDockCode());
		}else{
			entityCompanyDock = companyDockService.getCompanyDockInfo(request.getComAppid(), request.getDockCode());
		}
		if (entityCompanyDock == null) {
			return ResultUtil.error(ResultEnum.Err_1);
		}
		log.info("entityCompanyDock:" + entityCompanyDock.toString());
		Integer grade = 0;

		if (!CommonUtil.isNull(entityCompanyDock.getServerCode())) {
			if (CommonUtil.isNull(request.getSvrAppid())) {
				return ResultUtil.error(ResultEnum.Err_2);
			}
			EntityDockServer entityDockServer = dockServerService.getDockServerInfo(request.getDockCode(), request.getSvrAppid(), entityCompanyDock.getServerCode(), null);

			if (entityDockServer == null) {
				return ResultUtil.error(ResultEnum.Err_2);
			}
			log.info("entityDockServer:" + entityDockServer.toString());
			grade = 10;
		}

		EntityDockKey entityDockKey = dockKeyService.getDockKeyInfo(request.getDockCode(), grade, entityCompanyDock.getComId(), entityCompanyDock.getServerCode());
		if (entityDockKey == null) {
			return ResultUtil.error(ResultEnum.Err_3);
		}
		log.info("entityDockKey:" + entityDockKey.toString());
		String key = "";
		switch (request.getKeyType()) {
			case 0:
				key = entityDockKey.getMd5Key();
				break;
			case 1:
				key = entityDockKey.getRsaPub();
				break;
			case 2:
				key = entityDockKey.getRsaPri();
				break;
			case 3:
				key = entityDockKey.getRsa2Pub();
				break;
			case 4:
				key = entityDockKey.getRsa2Pri();
				break;
			case 5:
				key = entityDockKey.getSm3Key();
				break;
		}

		EntityComDockApi entityComDockApi = comDockApiService.getComDockApi(request.getDockCode(), entityCompanyDock.getComId(), request.getDockApiCode(), 0);
		if (entityComDockApi == null) {
			return ResultUtil.error(ResultEnum.Err_4);
		}

		entityComDockApi.setKey(key);
		log.info("entityComDockApi:" + entityComDockApi.toString());
		return ResultUtil.success(entityComDockApi);
	}

	/**
	 * 6.23生成单位登录验证码（getComLoginAuthCode）
	 */
	@PostMapping(CompanyServiceUrl.URL_getComLoginAuthCode)
	public Result getComLoginAuthCode(@RequestBody ComLoginAuthCodeRequest request) {
		String code = "XAK"+request.getComAppid()+ RandomUtil.getRandomString(20);
//		redisUtil.set("SsoCode:"+request.getServerCode()+":"+code,request);
		redisUtil.set("SsoCode:"+request.getServerCode()+":"+code,request,300l);
		return ResultUtil.success(code);
	}

	/**
	 * 6.24单位登录验证（comLoginAuth）
	 */
	@PostMapping(CompanyServiceUrl.URL_comLoginAuth)
	public Result comLoginAuth(String serverCode,String authCode) {
		Object ob = redisUtil.get("SsoCode:"+serverCode+":"+ authCode);
		if(ob==null){
			return ResultUtil.error(ResultEnum.Err_3079);
		}
		redisUtil.del("SsoCode:"+serverCode+":"+ authCode);
		//(ComLoginAuthCodeRequest) ob
		return ResultUtil.success(ob);
	}



	@PostMapping(CompanyServiceUrl.URL_getSeverReplyApiPara)
	public Result getSeverReplyApiPara(@RequestBody GetSeverReplyApiParaRequest request) {
		EntityDockServer entityDockServer = dockServerService.getDockServerInfo(request.getDockCode(),request.getSvrAppid(),null, null);
		if (entityDockServer == null) {
			return ResultUtil.error(ResultEnum.Err_3102);
		}

		EntityDockKey entityDockKey = dockKeyService.getDockKeyInfo(request.getDockCode(), 10, null, entityDockServer.getServerCode());
		if (entityDockKey == null) {
			return ResultUtil.error(ResultEnum.Err_3103);
		}
		String key = "";
		switch (request.getKeyType()) {
			case 0:
				key = entityDockKey.getMd5Key();
				break;
			case 1:
				key = entityDockKey.getRsaPub();
				break;
			case 2:
				key = entityDockKey.getRsaPri();
				break;
			case 3:
				key = entityDockKey.getRsa2Pub();
				break;
			case 4:
				key = entityDockKey.getRsa2Pri();
				break;
			case 5:
				key = entityDockKey.getSm3Key();
				break;
		}

		SrvCodeVo srvCodeVo =new SrvCodeVo();
		srvCodeVo.setSrvCode(entityDockServer.getServerCode());
		srvCodeVo.setKey(key);
		srvCodeVo.setComId(entityDockKey.getComId());
		srvCodeVo.setUrl("");


		EntityDockUrl entityDockUrl = dockUrlService.getDockUrl(request.getDockCode(),10,entityDockKey.getComId(),entityDockServer.getServerCode());
		if(entityDockUrl!=null){
			srvCodeVo.setUrl(entityDockUrl.getRequestUrl());
		}

		return ResultUtil.success(srvCodeVo);

	}


	@PostMapping(CompanyServiceUrl.URL_getComDockPageList)
	public Result getComDockPageList(Long comId) {
		List<ComDockApiListVo> list = comDockApiService.getComDockApiList(comId);
		if(list==null){
			return ResultUtil.success(new ArrayList<>());
		}
		return ResultUtil.success(list);
	}



	@PostMapping(CompanyServiceUrl.URL_getDockApiUrl)
	public Result getDockApiUrl(@RequestBody GetDockApiUrlRequest request) {
		List<DockApiUrlVo> list = dockApiService.getDockApiUrl(request.getDockCode(),
				request.getGrade(),
				request.getComId(),
				request.getServerCode()
		);
		if(list==null){
			return ResultUtil.success(new ArrayList<>());
		}
		return ResultUtil.success(list);

	}


	//6.5添加平台通讯接口（addDockApi）
	@PostMapping(CompanyServiceUrl.Url_addDockApi)
	public Result addDockApi(@RequestBody EntityDockApi request){
		List<EntityDockApi> list = dockApiService.getDockApiByDockCodeAndApiCode(request.getDockCode(), request.getDockApiCode());
		if (list != null && !list.isEmpty()) return ResultUtil.error(ResultEnum.Err_4090);

		list = dockApiService.getDockApiByDockCodeAndApiName(request.getDockCode(), request.getApiName());
		if (list != null && !list.isEmpty()) return ResultUtil.error(ResultEnum.Err_4091);

		dockApiService.save(request);
		return ResultUtil.success();
	}

	@PostMapping(CompanyServiceUrl.Url_updateDockApi)
	public Result updateDockApi(@RequestBody EntityDockApi request){
		List<EntityDockApi> list = dockApiService.getDockApiByDockCodeAndApiCode(request.getDockCode(), request.getDockApiCode());
		if (list == null || list.isEmpty()) return ResultUtil.error(ResultEnum.Err_4092);

		list = dockApiService.getDockApiByDockCodeAndApiNameAndNotApiCode(request.getDockCode(), request.getApiName(),request.getDockApiCode());
		if (list != null && !list.isEmpty()) return ResultUtil.error(ResultEnum.Err_4090);

		return ResultUtil.success(dockApiService.update(request));
	}

	@PostMapping(CompanyServiceUrl.Url_getDockApiList)
	public Result getDockApiList(@RequestBody DockApiListDto request){
		return ResultUtil.success(dockApiService.getPageDockApiList(request.getDockCode(), request.getDockApiCode(),request.getApiName(), 20, request.getPage(), request.getSize()));
	}

	@PostMapping(CompanyServiceUrl.Url_setDockApiUrl)
	public Result setDockApiUrl(@RequestBody EntityDockUrl request){
		dockUrlService.setDockApiUrl(request);
		return ResultUtil.success();
	}

	@PostMapping(CompanyServiceUrl.Url_getDockServerList)
	public Result getDockServerList(@RequestBody DockServerListDto request){
		Map<String, Object> parameters = new HashMap<>();
		if (StringUtils.isNotBlank(request.getServerCode())) {
			parameters.put("server_code",request.getServerCode());
		}
		if (StringUtils.isNotBlank(request.getServerName())) {
			parameters.put("server_name",request.getServerName());
		}
		return ResultUtil.success(dockServerService.getDockServerList(request.getDockCode(), parameters, request.getPage(), request.getSize()));
	}

	@PostMapping(CompanyServiceUrl.Url_addDockServer)
	public Result addDockServer(@RequestBody EntityDockServer request){
		return dockServerService.addDockServer(request);
	}

	@PostMapping(CompanyServiceUrl.Url_updateDockServer)
	public Result updateDockServer(@RequestBody EntityDockServer request){
		return dockServerService.updateDockServer(request);
	}

	@PostMapping(CompanyServiceUrl.Url_getComDockList)
	public Result getComDockList(@RequestBody CompanyDockListDto request){
		return ResultUtil.success(companyDockService.getComDockList(request.getComId()));
	}

	@PostMapping(CompanyServiceUrl.Url_getComDockApi)
	public Result getComDockApi(@RequestParam String dockCode,
								@RequestParam Long comId,
								@RequestParam String dockApiCode,
								@RequestParam Integer apiPermission){
		return ResultUtil.success(comDockApiService.getComDockApi(dockCode,comId,dockApiCode,apiPermission));
	}

	@PostMapping(CompanyServiceUrl.Url_addComDock)
	public Result addComDock(@RequestBody EntityCompanyDock request){
		return companyDockService.addComDock(request);
	}

	@PostMapping(CompanyServiceUrl.Url_updateComDock)
	public Result updateComDock(@RequestBody EntityCompanyDock request){
		return companyDockService.updateComDock(request);
	}

	@PostMapping(CompanyServiceUrl.Url_removeComDock)
	public Result removeComDock(@RequestBody EntityCompanyDock request){
		return companyDockService.removeComDock(request);
	}

	@PostMapping(CompanyServiceUrl.Url_getDockKey)
	public Result getDockKey(@RequestBody DockKeyDto request){
		return ResultUtil.success(dockKeyService.getDockKeyInfoReturnNew(request.getDockCode(), request.getGrade(),request.getComId(),request.getServerCode()));
	}

	@PostMapping(CompanyServiceUrl.Url_saveDockKey)
	public Result saveDockKey(@RequestBody EntityDockKey request){
		return ResultUtil.success(dockKeyService.saveDockKey(request));
	}

	@PostMapping(CompanyServiceUrl.Url_getDockApiConfig)
	public Result getDockApiConfig(@RequestBody GetDockApiConfigDto request){
		return ResultUtil.success(comDockApiService.getDockApiConfig(request.getComId(), request.getDockCode()));
	}

	@PostMapping(CompanyServiceUrl.Url_saveDockApiConfig)
	public Result saveDockApiConfig(@RequestBody EntityComDockApi request){
		return  ResultUtil.success(comDockApiService.saveDockApiConfig(request));
	}

	@PostMapping(CompanyServiceUrl.Url_getDockComList)
	public Result getDockComList(@RequestBody CompanyDockComListDto request){
		return ResultUtil.success(companyDockService.getDockComList(request.getDockCode(), request.getServerCode()));
	}

	@PostMapping(CompanyServiceUrl.Url_getApiPara)
	public Result getApiPara(@RequestParam("comId") Long comId, @RequestParam("dockApiCode") String dockApiCode){
		return  ResultUtil.success(comDockApiService.getApiPara(comId, dockApiCode));
	}

	@PostMapping(CompanyServiceUrl.Url_setApiPara)
	public Result setApiPara(@RequestParam("comId") Long comId, @RequestParam("dockApiCode") String dockApiCode, @RequestParam("apiPara") String apiPara){
		return  ResultUtil.success(comDockApiService.setApiPara(comId, dockApiCode, apiPara));
	}

	@PostMapping(CompanyServiceUrl.Url_getApiList)
	public Result getApiList(@RequestBody GetApiListRequest request){
		return  ResultUtil.success(comDockApiService.getApiList(request));
	}

	@PostMapping(CompanyServiceUrl.URL_getComRequest)
	public Result getComRequest(@RequestBody GetComRequestRequest request) {
		String key = "getComRequest:"+request.getComId() + ":" + request.getDockCode() + ":" + request.getDockApiCode();
		GetComRequestResponse response = new GetComRequestResponse();

		Object ob = redisUtil.get(key);

		if(ob != null){
			response = JSON.parseObject(JSON.toJSONString(ob), GetComRequestResponse.class);

		} else {

			EntityCompanyDock entityCompanyDock = companyDockService.getCompanyDock(false, request.getComId(), request.getDockCode(), null);
			if (entityCompanyDock == null) {
				return ResultUtil.error(ResultEnum.Err_1);
			}
			response.setComAppid(entityCompanyDock.getComAppid());
			response.setServerCode(entityCompanyDock.getServerCode());
			Integer grade = 0;

			if (StringUtils.isNotBlank(entityCompanyDock.getServerCode())) {
				response.setServerCode(entityCompanyDock.getServerCode());

				EntityDockServer entityDockServer = dockServerService.getDockServerInfo(request.getDockCode(), null, entityCompanyDock.getServerCode(), null);
				if (entityDockServer == null) {
					return ResultUtil.error(ResultEnum.Err_2);
				}
				response.setSvrAppid(entityDockServer.getSvrAppid());
				grade = 10;
			}


			EntityDockKey entityDockKey = dockKeyService.getDockKeyInfo(request.getDockCode(), grade, entityCompanyDock.getComId(), entityCompanyDock.getServerCode());
			if (entityDockKey == null) {
				return ResultUtil.error(ResultEnum.Err_3);
			}
			response.setMd5key(entityDockKey.getMd5Key());
			response.setRsaPub(entityDockKey.getRsaPub());
			response.setRsaPri(entityDockKey.getRsaPri());
			response.setRsa2Pub(entityDockKey.getRsa2Pub());
			response.setRsa2Pri(entityDockKey.getRsa2Pri());


			EntityDockUrl entityDockUrl = dockUrlService.getDockUrl(request.getDockCode(),grade, request.getComId(),response.getServerCode(),request.getDockApiCode());
			if (entityDockUrl != null) {
				response.setRequestUrl(entityDockUrl.getRequestUrl());
			}
			redisUtil.set(key , response, 2 * 60l);
		}

		return ResultUtil.success(response);
	}


	@PostMapping(HumanServiceUrl.URL_getFeatureVersion)
	public Result getFeatureVersion(@RequestParam("companyId") Long companyId){
		return ResultUtil.success(comDockApiService.getFeatureVersion(companyId));
	}
}

